import { BusinessException } from './../common/exceptions/business.exception'
import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { User } from 'src/entity/User'
import { UserInfo } from 'src/entity/Userinfo'
import { UsersService } from 'src/users/users.service'
import { enCode } from 'src/utils'
import { Connection, Repository } from 'typeorm'

@Injectable()
export class UserInfoService {
  constructor(
    @InjectRepository(UserInfo)
    private userInfoRepository: Repository<UserInfo>,
    private connection: Connection,
    private readonly usersService: UsersService,
  ) { }

  // userId -> *
  async findOne(id: number) {
    return await this.userInfoRepository.findOne({
      where: { userId: id },
    })
  }

  // 新增用户和用户数据
  // userName, password -> new User, new UserInfo
  async register(data) {
    const {
      userName,
      password,
      orgId,
      orgName,
    }: {
      userName: string
      password: string
      orgId: number
      orgName: string
    } = data
    const isExist = await this.usersService.findOne(userName)
    console.log('userName, password4', userName, password, isExist)
    if (isExist) throw new BusinessException('用户名已存在')

    const user = new User()
    user.userName = userName
    user.password = enCode(password)
    let userInfoSqlData = null
    await this.connection.transaction(async (manager) => {
      const sqlData = await manager.save(user)
      const userInfoData = { ...data }
      if (userInfoData.password) delete userInfoData.password
      if (!userInfoData.disable) userInfoData.disable = false
      userInfoData.userId = sqlData.id
      userInfoSqlData = await manager.save(UserInfo, userInfoData)
    })
    return userInfoSqlData
  }

  // id -> delete user, userInfo
  async delete(id: number) {
    console.log('id', id)

    await this.connection.transaction(async (manager) => {
      const sql = await manager.update(
        User,
        {
          id,
        },
        {
          isDelete: true,
        },
      )
      const find = await manager.findOne(User, {
        where: {
          id,
        },
      })
      console.log('sql', find, sql)

      await manager.update(
        UserInfo,
        { userId: id },
        {
          isDelete: true,
        },
      )
    })
    return {}
  }

  // 通过userId新指定属性值
  async update(data: {
    userId: number
    property: string[]
    propertyValue: any[]
  }) {
    const value: any = {}
    data.property.forEach((item, index) => {
      value[item] = data.propertyValue[index]
    })
    return await this.userInfoRepository.update({ userId: data.userId }, value)
  }
}
